package work.easy.monitor;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.*;

/**
 * @author YueXiao
 * @date 2017/11/16
 */
public class HttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    private static <T> T executeFor(HttpUriRequest request, Class<T> clazz) throws IOException {
        HttpClient httpclient = HttpClients.createDefault();
        HttpResponse response = httpclient.execute(request);
        String result = EntityUtils.toString(response.getEntity(), "utf-8");

        StatusLine statusLine = response.getStatusLine();

        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            if (String.class == clazz) {
                return clazz.cast(result);
            }
            return JSON.parseObject(result, clazz);
        } else {
            logger.error("Error! postObjectFor request=[{}],Http Status=[{}],responseText=[{}]", request, statusLine, result);
            return null;
        }
    }

    public static <T> T getFor(String url, Class<T> clazz) {
        HttpGet httpGet = new HttpGet(url);
        try {
            return executeFor(httpGet, clazz);
        } catch (IOException e) {
            logger.error("Error! getFor url=[{}]", url, e);
            return null;
        }

    }

    public static <T> T postFormFor(String url, Map<String, Object> params, Class<T> clazz) {
        HttpPost httppost = new HttpPost(url);
        httppost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");

        List<NameValuePair> nameValuePairs = new ArrayList<>();

        Set<Map.Entry<String, Object>> entrySet = params.entrySet();

        for (Map.Entry<String, Object> entry : entrySet) {
            Object value = entry.getValue();
            if (value != null) {
                NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), Objects.toString(value));
                nameValuePairs.add(nameValuePair);
            }
        }

        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
            httppost.setEntity(entity);
            return executeFor(httppost, clazz);
        } catch (IOException e) {
            logger.error("Error! postObjectFor url=[{}],body=[{}]", url, params, e);
            return null;
        }
    }


    public static <T> T postObjectFor(String url, Object body, Class<T> clazz) {

        HttpPost httppost = new HttpPost(url);
        httppost.addHeader("Content-Type", "application/json; charset=utf-8");

        String textMsg = JSON.toJSONString(body);
        StringEntity entity = new StringEntity(textMsg, "utf-8");
        httppost.setEntity(entity);

        try {
            return executeFor(httppost, clazz);
        } catch (IOException e) {
            logger.error("Error! postObjectFor url=[{}],body=[{}]", url, body, e);
            return null;
        }
    }
}
